package components.utils.observer;

import entity.ServiceRequest;
import java.util.Collection;
import java.util.List;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TreeUpdater extends CollectionObserver {
    
    private JTree tree;
    private int childToUpdate;

    public TreeUpdater(Collection collection, JTree tree, int childToUpdate) {
        super(collection);
        this.tree = tree;
        this.childToUpdate = childToUpdate;
    }

    @Override
    public void notifyObserver() {
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        DefaultMutableTreeNode updatingNode = (DefaultMutableTreeNode) root.getChildAt(childToUpdate);
        
        updatingNode.removeAllChildren();
        
        //Add the new children.
        for (Object entity : collection) {
            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(entity);
            if (entity instanceof ServiceRequest) {
                ServiceRequest serviceRequest = (ServiceRequest) entity;
                List samples = serviceRequest.getSamples();
                //Add the samples as child nodes.
                for (Object sample : samples) {
                    newNode.add(new DefaultMutableTreeNode(sample));
                }
            }
            updatingNode.add(newNode);
        }
        
        //Notify the model of the changes made.
        model.reload(updatingNode);
    }

}
